package com._reflect;

import zzzzz_just_for_test.FFF;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * @Author: huangya
 * @Date: 2019/9/10
 * @Description:
 */
public class _MethodHandleDemo {

    public static void main(String[] args) throws Throwable {
        /** 调用String的replace方法 */
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType mt = MethodType.methodType(String.class,char.class,char.class);
        try {
            MethodHandle mh = lookup.findVirtual(String.class,"replace", mt);
            String handled_str = (String) mh.invoke("abc",'a','c');
            System.out.print(handled_str);
        } catch (NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }

        /** 调用FFF类的fff方法 */
        MethodHandles.Lookup lookup222 = MethodHandles.lookup();
        MethodType mt222 = MethodType.methodType(void.class);
        try {
            MethodHandle mh222 = lookup222.findVirtual(FFF.class,"fff", mt222);
            mh222.invoke(new FFF());
        } catch (NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }

        /** 调用FFF类的staticfff静态方法 */
        MethodHandles.Lookup lookup333 = MethodHandles.lookup();
        MethodType mt333 = MethodType.methodType(void.class);
        try {
            MethodHandle mh333 = lookup333.findStatic(FFF.class,"staticfff", mt333);
            mh333.invoke();
        } catch (NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
